//
//  ViewController.m
//  WebServ1
//
//  Created by Job Search on 27/07/14.
//
//

#import "ViewController.h"
#import "NSDictionary+JSONCategories.h"

@interface ViewController ()


@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _dataArray = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", nil];
    _picker.delegate = self;
     [self updateAll:1];

}

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [_dataArray count];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [self updateAll:row];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    return [_dataArray objectAtIndex:row];
}

-(void) updateAll: (int) index
{
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   
                   ,
                   
                   ^{
                       // Do any additional setup after loading the view, typically from a nib.
                       NSDictionary* myInfo = [NSDictionary dictionaryWithContentsOfJSONURLString: @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"];
                       
                       //if no connection return
                       if(!myInfo) return;
                       
                       NSArray* latestLoans = [myInfo objectForKey:@"loans"]; //2
                       
                       // 1) Get the latest loan
                       NSDictionary* loan = [latestLoans objectAtIndex:index];
                       
                       [self performSelectorOnMainThread:@selector(kivawsFoundraising:) withObject:loan waitUntilDone:YES];
                       
                   });
}


-(void) kivawsFoundraising: (NSDictionary *) loan
{
    _pickerLabel.text = [NSString stringWithFormat:@"Loan nr. %@ in text presentation: ", [_dataArray objectAtIndex:[_picker selectedRowInComponent:0]]];
    [self writeReadableLabel:loan];
    [self writeJsonLabel:loan];
}

-(void) writeReadableLabel : ( NSDictionary *) loan
{
    // 2) Get the funded amount and loan amount
    NSNumber* fundedAmount = [loan objectForKey:@"funded_amount"];
    NSNumber* loanAmount = [loan objectForKey:@"loan_amount"];
    float outstandingAmount = [loanAmount floatValue] -
    [fundedAmount floatValue];
    
    // 3) Set the label appropriately
    _readableLabel.text = [NSString stringWithFormat:@"Latest loan: %@ from %@ needs another $%.2f to pursue their entrepreneural dream ",
                           [loan objectForKey:@"name"],
                           [(NSDictionary*)[loan objectForKey:@"location"]
                            objectForKey:@"country"],
                           outstandingAmount];
}

-(void) writeJsonLabel  : ( NSDictionary *) loan{
    NSNumber* fundedAmount = [loan objectForKey:@"funded_amount"];
    NSNumber* loanAmount = [loan objectForKey:@"loan_amount"];
    float outstandingAmount = [loanAmount floatValue] -
    [fundedAmount floatValue];
    NSError* error = nil;
    
    //build an info object and convert to json
    NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
                          [loan objectForKey:@"name"],
                          @"who",
                          [(NSDictionary*)[loan objectForKey:@"location"]
                           objectForKey:@"country"],
                          @"where",
                          [NSNumber numberWithFloat: outstandingAmount],
                          @"what",
                          nil];
    
    //convert object to data
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:info 
                                                       options:NSJSONWritingPrettyPrinted error:&error];
    
    _jsonLabel.text = [[NSString alloc] initWithData:jsonData
                                            encoding:NSUTF8StringEncoding];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
